package me.zzp.controller;

import me.zzp.domain.Condition;
import me.zzp.domain.Page;
import me.zzp.domain.Pageable;
import me.zzp.feature.Json;
import me.zzp.mapper.UserMapper;
import me.zzp.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;

import static me.zzp.domain.Condition.and;
import static me.zzp.domain.Condition.eq;

/**
 * @author zhangzepeng
 */
@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserMapper userMapper;

    @RequestMapping(method = RequestMethod.GET)
    public Iterable<User> index(@Json Condition condition, Pageable pageable) {
        List<User> users = userMapper.findAllBy(condition, new HashMap<>(), pageable);
        if (pageable != null) {
            int total = userMapper.countBy(condition, new HashMap<>());
            return new Page(users, pageable.getPage(), pageable.getSize(), total);
        } else {
            return users;
        }
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public User show(@PathVariable int id) {
        return userMapper.findOne(id);
    }

    @RequestMapping(method = RequestMethod.POST)
    public User create(@Json("model") User user) {
        return userMapper.create(user) > 0? userMapper.findOne(user.getId()): null;
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.PATCH)
    public int update(@PathVariable int id, @Json("model") User user) {
        return userMapper.updateBy(and(eq("id", id), eq("version", user.getVersion())), new HashMap<>(), user);
    }

    @RequestMapping(method = RequestMethod.PUT)
    public int update(@Json Condition condition, @Json("model") User user) {
        return userMapper.updateBy(condition, new HashMap<>(), user);
    }

    @RequestMapping(method = RequestMethod.DELETE)
    public int destroy(@Json Condition condition) {
        return userMapper.destroyBy(condition, new HashMap<>());
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public int destroy(@PathVariable int id, @RequestParam(required = false, defaultValue = "0") int version) {
        Condition condition = eq("id", id);
        if (version > 0) {
            condition = and(condition, eq("version", version));
        }
        return userMapper.destroyBy(condition, new HashMap<>());
    }
}
